package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.util.FormHelper;
import struts.util.XmlBean;

/**
 * 
 * 
 * @author zhouhong
 * @date 2014-9-21 新建
 */
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = -7127150859111716940L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("----------------++++++++++");
		// 获得请求头
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		ServletContext context = req.getServletContext();
		//一、通过UserLogin.html提交表单reqUrl为下面这个，需要进行切分下
		String reqUrl = req.getServletPath().split("/")[2];
		//二、通过UserLogin.jsp提交表单reqUrl为下面这个
		//String reqUrl = req.getServletPath();
		Map<String, XmlBean> map = (Map<String, XmlBean>) context.getAttribute("struts");
		
		XmlBean xml = map.get(reqUrl);
		
		try {
			//逆向生成Form类
			ActionForm form = FormHelper.createForm(req , xml.getFormClass());
			
			//通过配置文件得到Action类
			Class actionClass = Class.forName(xml.getActionClass());
			Action action = (Action) actionClass.newInstance();
			
			String url = action.execute(req, resp, form, xml.getActionForward());
			
			req.getRequestDispatcher(url).forward(req, resp); //跳转到指定页面
			
		} catch (Exception e) {
			System.out.println();
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
